package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.bean.CartOrderUuBean;
import com.atguigu.edu.util.ClickHouseUtil;
import com.atguigu.edu.util.DateFormatUtil;
import com.atguigu.edu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserOrderWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1 获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //设置并行度
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 2 设置检查点和状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //TODO 3 从kafka中读取对应数据
        String groupId = "dws_user_order_window";
        String topicName = "dwd_trade_order_detail";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 4 转化结构
        SingleOutputStreamOperator<JSONObject> jsonObjStream = streamSource.map(JSON::parseObject);

        //TODO 5 根据用户分组并根据状态去重
        SingleOutputStreamOperator<CartOrderUuBean> beanStream =
                jsonObjStream.keyBy(s -> s.getString("user_id"))
                .flatMap(new RichFlatMapFunction<JSONObject, CartOrderUuBean>() {
                    ValueState<String> lastOrderDtState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastOrderDtState =
                                getRuntimeContext().getState(new ValueStateDescriptor<String>("last_order_dt",
                                        String.class));
                    }

                    @Override
                    public void flatMap(JSONObject value, Collector<CartOrderUuBean> out) throws Exception {
                        String lastOrderDt = lastOrderDtState.value();
                        Long ts = DateFormatUtil.toTs(value.getString("create_time"), true);
                        String orderDt = DateFormatUtil.toDate(ts);
                        if (lastOrderDt == null) {
                            //首次下单
                            out.collect(new CartOrderUuBean("","",1L,1L,ts));
                            lastOrderDtState.update(orderDt);
                        }
                        if (!orderDt.equals(lastOrderDt)){
                            //独立下单
                            out.collect(new CartOrderUuBean("","",1L,0L,ts));

                        }
                    }
                });


        //TODO 6 设置水位线
        SingleOutputStreamOperator<CartOrderUuBean> beanWithWaterMarkStream =
                beanStream.assignTimestampsAndWatermarks(WatermarkStrategy.<CartOrderUuBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<CartOrderUuBean>() {
                    @Override
                    public long extractTimestamp(CartOrderUuBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));

        //TODO 7 开窗聚合
        SingleOutputStreamOperator<CartOrderUuBean> resultStream =
                beanWithWaterMarkStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<CartOrderUuBean>() {
                    @Override
                    public CartOrderUuBean reduce(CartOrderUuBean value1, CartOrderUuBean value2) throws Exception {
                        value1.setCartOrdUuCt(value1.getCartOrdUuCt() + value2.getCartOrdUuCt());
                        value1.setCartNewUserOrderCt(value1.getCartNewUserOrderCt() + value2.getCartNewUserOrderCt());
                        return value1;
                    }
                }, new AllWindowFunction<CartOrderUuBean, CartOrderUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<CartOrderUuBean> values,
                                      Collector<CartOrderUuBean> out) throws Exception {
                        CartOrderUuBean cartOrderUuBean = values.iterator().next();
                        cartOrderUuBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        cartOrderUuBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        cartOrderUuBean.setTs(System.currentTimeMillis());
                        out.collect(cartOrderUuBean);
                    }
                });

        //TODO 8 写入到clickhouse中
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_user_order_window values(?,?,?,?," +
                "?)"));

        // TODO  执行任务
        env.execute(groupId);
    }
}
